<template>
  <div class="wrap">
    <div class="labelBox">
      <el-row class="line36">
        <el-col :span="4" :offset="16">
          <el-button type="warning" @click="addAccount">新增子账号</el-button>
        </el-col>
      </el-row>
      <el-table
        border
        :data="tableData"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        style="width: 100%"
        ref="multipleTable"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
      >
        <el-table-column prop="mobile" label="账号" />
        <el-table-column prop="role" label="权限" >
          <template slot-scope="scope">
            {{returnrole(scope.row.role)}}
          </template>
        </el-table-column>
        <el-table-column prop="truename" label="负责人" />
        <el-table-column prop="station_num" label="管理站点" />
        <el-table-column prop="isRegister" label="状态">
          <template slot-scope="scope">
            {{ scope.row.isRegister ? "已注册" : "未注册" }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="success"
              size="mini"
              @click="edit(scope.row.mobile, scope.row.id, scope.row.truename, scope.row.admin_id, scope.row.league_id)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block mt-20">
        <el-row justify="center" type="flex">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="pageIndex"
            :limit.sync="pageSize"
            @pagination="GetChildAccountManagementList"
          />
        </el-row>
      </div>
    </div>

    <el-dialog
      :title="this.disable ? '修改子账户' : '新增子账户'"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      center
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="150px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="所属合伙人企业" prop="companyname">
          <el-input
            v-model="ruleForm.companyname"
            disabled
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="admin_name">
          <el-input
            v-model="ruleForm.admin_name"
            :disabled="disable"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="admin_mobile">
          <el-input
            v-model="ruleForm.admin_mobile"
            :disabled="disable"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="授权管理站点" prop="station_id">
          <el-transfer
            style="text-align: left; display: inline-block"
            v-model="checkedData"
            :left-default-checked="[]"
            :right-default-checked="[]"
            :titles="['待选择洗车站', '已选站点']"
            :button-texts="['<<', '>>']"
            :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}',
            }"
            @change="handleChange"
            :data="disable ? allMageMent : sqdata"
          >
            <span slot-scope="{ option }">{{ option.label }}</span>
          </el-transfer>
        </el-form-item>
        <el-row class="bg555" v-if="!disable">
          <el-col :offset="2">
            <p>授权说明:</p>

            <p>
              注:已绑定洗车站信息或者被其他管理主体授权管理站点的账号不能再次授权
            </p>
            <p>1、选择-个或多个门店进行授权</p>
            <p>2、输入会员手机号</p>
            <p>3、点击发送确认，系统向该用户发送手机短信</p>
            <p>4、下载商户端APP/小程序激活授权</p>
          </el-col>
        </el-row>
        <!-- <el-form-item> -->
        <el-row justify="center">
          <el-col :span="24" class="text-center">
            <el-button type="primary" @click="submitForm('ruleForm')"
              >确认</el-button
            >
            <el-button v-if="!disable" @click="resetForm('ruleForm')"
              >重置</el-button
            >
          </el-col>
        </el-row>
        <!-- </el-form-item> -->
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { set } from "nprogress";
export default {
  name: "",
  data() {
    return {
      checkedData: [], ///选择的站点
      tableData: [], //子账户列表
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false, //弹框状态
      ruleForm: {
        //新增编辑表单
        league_id: "",
        station_id: [],
        station_name: [],
        admin_name: "",
        admin_mobile: "",
        companyname: "",
      },

      id: "", //店铺id
      sqdata: [], //新增 站点列表
      allMageMent: [], //所有站点列表
      checkedMageMent: [], //已选择站点列表
      disable: true, //是否能编辑

      rules: {
        companyname: [
          { required: true, message: "请输入企业全称", trigger: "blur" },
        ],
        admin_name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
        ],
        admin_mobile: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
        ],
        station_id: [
          { required: true, message: "请选择站点", trigger: "blur" },
        ],
      },
      role:[{role:0,name:'员工'},{role:1,name:'管理员'},{role:2,name:'超级管理员'},{role:3,name:'自助洗车站点管理员'}]
    };
  },
  created() {
    this.id = this.$route.query.storeId;
    this.ruleForm.league_id = this.$route.query.storeId;
    this.ruleForm.companyname = this.$route.query.companyname;
    // console.log(this.$route.query.storeId);
    this.GetChildAccountManagementList();
  },
  methods: {
    // 获取子账号列表
    GetChildAccountManagementList() {
      let data = {
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        storeid: this.id,
      };
      this.$api.washCarUser.GetChildAccountManagementList(data).then((res) => {
        // console.log(res);
        this.tableData = res.data.list;
        this.total = res.data.total;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 修改
    edit(mobile, id, name,admin_id,league_id) {
      // console.log(mobile, id, name)
      // if (id) {
        this.ruleForm.admin_id=admin_id
        this.ruleForm.league_id=league_id
        this.ruleForm.admin_name = name;
        this.ruleForm.admin_mobile = mobile;
        this.ruleForm.id = id;
        this.dialogVisible = true;
        this.disable = true;
      // }else{
      //   this.ruleForm.admin_name = name;
      //   this.ruleForm.admin_mobile = mobile;
      //   this.ruleForm.id = id;
      //   this.dialogVisible = true;
      //   this.disable = true;
      // }

      Promise.all([
        this.GetStationListManagementByStoreId(false, "", true, "allMageMent"), //获取未管理的站点
        this.GetStationListManagementByStoreId(
          true,
          mobile,
          false,
          "checkedMageMent"
        ), //获取已管理的站点
      ]).then((values) => {
        let list = [];
        // 获取未选择的站点和已选择的站点 并合并
        this.allMageMent = this.allMageMent.concat(values[1]);
        console.log(values, this.allMageMent, this.checkedMageMent);
        if (values[0].length === 0 && values[1].length > 0) {
          this.checkedMageMent.forEach((i, index) => {
            this.checkedData.push(index);
          });
        } else if (values[0].length > 0 && values[1].length > 0) {
          this.allMageMent.map((x, index) => {
            x.key = index;
            values[1].map((k) => {
              if (x.id == k.id) {
                return list.push(index);
              }
            });
          });
          // 筛选已选择的站点（主要为了组件处理数据）
          this.checkedData = list;
        }
      });

      //  已选择的
    },
    // 获取站点列表
    async GetStationListManagementByStoreId(ismanaged, mobile, isboss, table) {
      console.log(table);
      //ismanaged、isboss 新增 true  修改false
      let data = {
        pageIndex: 1,
        pageSize: 100,
        storeid: this.id,
        ismanaged: ismanaged,
        mobile: mobile,
        isboss: isboss,
      };
      try {
        const res =
          await this.$api.washCarUser.GetStationListManagementByStoreId(data);

        this[table] = res.data.list;
        this[table].forEach((it, index) => {
          it.key = index;
          it.label = it.station_Name;
        });
        console.log(res, this.sqdata);
        return this[table];
      } catch (error) {
        console.log(error);
      }
    },
    returnrole(id){
      let name=''
      this.role.forEach(it=>{
        if(it.role==id){
          name=it.name
        }
      })
      return name
    },
    // 关闭弹窗
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          this.$nextTick(() => {
            this.resetForm("ruleForm");
          });
          done();
        })
        .catch((_) => {});
    },
    // 新增修改子账户
    submitForm() {
      // console.log(this.ruleForm);
      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) {
          return false;
        } else {
          let _this = this;

          if (this.disable) {
            let list = [];
            // 筛选出取消的站点
            this.checkedMageMent.forEach((x) => {
              this.ruleForm.station_id.forEach((k) => {
                console.log(x,k)
                if (x.id == k) {

                }else{
                    list.push(x.id);
                }
              });
            });
            console.log(list);
            this.ruleForm.cancel_Station_id = Array.from(new Set(list));
          }
          console.log(this.ruleForm, this.disable);
          let promise = this.disable
            ? this.$api.washCarUser.EditAddChildAccountCarWashManagement(
                this.ruleForm
              )
            : this.$api.washCarUser.AddChildAccountCarWashManagement(
                this.ruleForm
              );
          promise
            .then((res) => {
              console.log(res);
              // if (res.code === 200) {
              this.$message({
                message: res.data,
                type: "success",
                duration: 1500,
              });
              setTimeout(() => {
                this.dialogVisible = false;
                this.resetForm("ruleForm");
                this.pageIndex = 1;
                this.GetChildAccountManagementList();
              }, 1500);
              // }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 穿梭框事件
    handleChange(value, direction, movedKeys) {
      console.log(this.checkedData);
      this.ruleForm.station_id = [];
      this.ruleForm.station_name = [];
      this.checkedData.forEach((i) => {
        console.log(i);
        this.ruleForm.station_id.push(
          this.disable ? this.allMageMent[i].id : this.sqdata[i].id
        );
        this.ruleForm.station_name.push(
          this.disable
            ? this.allMageMent[i].station_Name
            : this.sqdata[i].station_Name
        );
      });
      console.log(
        this.checkedData,
        this.allMageMent,
        this.ruleForm.station_id,
        this.ruleForm.station_name
      );
    },
    // 新增子账户
    addAccount() {
      this.GetStationListManagementByStoreId(false, "", true, "sqdata").then(
        (res) => {
          console.log(res);
          this.dialogVisible = true;
          this.disable = false;
          this.$nextTick(() => {
            this.resetForm("ruleForm");
          });
        }
      );
    },
  },
};
</script>
<style scoped lang='scss'>
.wrap {
  width: 100%;
  padding: 10px;
  background: #f5f5f5;
}
.labelBox {
  background: #fff;
  padding: 10px;
}
.block {
  text-align: right;
}
.detailContent {
  .row {
    padding: 10px;
  }
}
.bg555 {
  width: 60%;
  margin: 20px auto;
  background: #f2f2f2;
  border-radius: 10px;
  padding: 10px 0px;
}
</style>
